import json
import os.path


import openpyxl
from openpyxl import Workbook
from openpyxl.worksheet.worksheet import Worksheet
from common.dolog import DoLog
dl = DoLog()
myLogger=dl.getLogger(__name__)
mypath = r'D:\Pycharm-work\autoOne\common'
class DoDile():
    # 读取文件
    def doTextRead(self):
        try:
            fileName = r'D:\Pycharm-work\2506p\myDatas\add.txt'
            # f = open(fileName, encoding='utf-8')
            # print(f.read())
            with open(fileName, encoding='utf-8') as f:
                print(f.read())
        except Exception as e:
            print(f'发生异常，异常是{e}')
            myLogger.info(e)
        else:
            myLogger.info('正常执行无异常')
    # 写入文件
    def doTextWrite(self):
        try:
            fileName = r'D:\Pycharm-work\2506p\myDatas\add.txt'
            f = open(fileName,mode='a', encoding='utf-8')
            # 写
            f.write('awfafaw')
            f.close()
        except Exception as e:
            print(f'发生异常，异常是{e}')
            myLogger.info(e)
        else:
            myLogger.info('正常执行无异常')
    # # 读取图片
    # def doPNGReda(self):
    #     fileName=r'D:\Pycharm-work\2506p\myDatas\meinv.png'
    #     with open(fileName,mode='r+b')as f:
    #         print(f,type(f))
    #         a = f.read()
    #         return a
    # # 生成图片
    # def doPNGWrite(self,fName,strs):
    #     fileName = rf'D:\Pycharm-work\2506p\myDatas\{fName}'
    #     with open(fileName,mode='w+b')as f:
    #         f.write(strs)
    # 字典转成json格式的字符串
    def doDictOJsonStr(self,d):
        try:
            s = json.dumps(d)
            print(s,type(s))
            myLogger.info('正常执行无异常')
            return s
        except Exception as e:
            print(f'发生异常，异常是{e}')
            myLogger.info(e)


    # josn格式的字符串转换成字典
    def doJsonODictStr(self,josonS):
        try:
            d = json.loads(josonS)
            print(d,type(d))
        except Exception as e:
            print(f'发生异常，异常是{e}')
            myLogger.info(e)
        else:
            myLogger.info('正常执行无异常')
    # 字典中的内容保存成json格式文件
    def doDictOJson(self, d, fname):
        fileName = os.path.join(mypath,fname)
        try:
            with open(fileName,mode='a',encoding='utf-8') as f:
                j = json.dump(d,f)
                print(f"成功读取字典内容数据: {j}{type(j)}")
                myLogger.info()
                return j
        except Exception as e:
            print(f'发生异常，异常是{e}')
            myLogger.info(e)

    # json格式文件提取出并转成字典
    def doJsonODict(self,fname):
        fileName = os.path.join(mypath,fname)
        try:
            with open(fileName,mode='r',encoding='utf-8') as f:
                d = json.load(f)
                print(f"成功读取JSON数据: {d}{type(d)}")
                myLogger.info('正常执行无异常')
                return d
        except Exception as e:
            print(f'发生异常，异常是{e}')
            myLogger.info(e)
        # except FileNotFoundError:
        #     raise FileNotFoundError(f"文件 {fileName} 不存在")
        # except json.JSONDecodeError as e:
        #     raise ValueError(f"文件 {fileName} 包含无效的JSON格式: {e}")
        # except PermissionError:
        #     raise PermissionError(f"没有权限读取文件 {fileName}")
        # except Exception as e:
        #     raise RuntimeError(f"读取文件 {fileName} 时发生错误: {e}")

    # 处理excel文件,读、写
    def doExcelRead(self,fname):
        fileName = os.path.join(mypath,fname)
        try:
            wk:Workbook=openpyxl.load_workbook(fileName)   # 获取工作簿的对象
            st:Worksheet = wk["ac"] # 通过工作簿对象获取sheet对象
            print(st,type(st))

            ss = st.iter_rows(values_only=True) # 获取sheet页中的值
            print(ss)
            print(range(10))
        except Exception as e:
            print(f'发生异常，异常是{e}')
            myLogger.info(e)
        else:
            l=[i for i in ss]   # 生成列表并返回
            print(f'{l}')

            myLogger.info('正常执行无异常')
            return l
    # 处理excel文件,读、写(部分)
    def doExcelReadDIV(self,fname,stname,minRow=None,maxRow=None
                       ,minCol=None,maxCol=None):
        fileName = os.path.join(mypath,fname)

        wk:Workbook=openpyxl.load_workbook(fileName)   # 获取工作簿的对象
        st:Worksheet = wk[stname] # 通过工作簿对象获取sheet对象
        print(st,type(st))
        # 提取部分数据

        ss = st.iter_rows(min_row=minRow,
                          max_row=maxRow,
                          min_col=minCol,
                          max_col=maxCol,
                          values_only=True) # 获取sheet页中的值



        l=[i for i in ss]   # 生成列表并返回
        print(f'{l}')



        return l
    # 写入表格
    def doExceWrite(self,fname,stname,ss):
        fileName = os.path.join(mypath, fname)  # 新文件名

        wk = openpyxl.Workbook()    # 创建新文件
        st:Worksheet = wk.create_sheet(stname,1)    # 创建sheet对象

        st.cell(1,1,ss)     # 写一个单元格
        wk.save(fileName)   # 保存

if __name__ == '__main__':

    df=DoDile()
    # df.doExceWrite('fileName.xlsx','one','anfoianw')
    # df.doTextRead()
    # df.doPNGReda()
    # #df.doTextWrite('dawfa')
    # sss=df.doPNGReda()      # 读取一个文件
    # fileName='meinv3.png'
    # df.doPNGWrite(fileName,sss) # 写一个文件
# 转换
#     # 字典转成json格式的字符串
#     dic = {'name':'zhangsan','age':23}
#     s=df.doDictOJsonStr(dic)
#     # josn格式的字符串转换成字典
#     df.doJsonODictStr(s)
#     # 字典中的内容保存成json格式文件
#     fileName = 'haoyu.json'
#     df.doDictOJson(dic,fileName)
#     # json格式文件提取出并转成字典
#     df.doJsonODict(fileName)
    df.doExcelReadDIV('yongli.xlsx','Sheet1',2,12,3,5)

















